﻿using Basic.FormDAL;
using Basic.FormRemoteModel.PhysicalPage.Model;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class PhysicalPageCollect : IPhysicalPageCollect
    {
        private readonly IPhysicalPageDAL _BasicDAL;

        public PhysicalPageCollect ( IPhysicalPageDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }
        public Result[] GetsByFormId<Result> ( long formId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.FormId == formId);
        }
        public void Clear ( long formId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FormId == formId, a => a.Id);
            if ( ids.IsNull() )
            {
                return;
            }
            this._BasicDAL.Delete(ids);
        }
        public long Set ( PhysicalPageSet set )
        {
            var res = this._BasicDAL.Find(a => a.FormId == set.FormId && a.PageType == set.PageType, a => new
            {
                a.Id,
                a.PagePath
            });
            if ( set.PagePath.IsNull() && res != null )
            {
                this._BasicDAL.Delete(res.Id);
            }
            else if ( res == null && set.PagePath.IsNull() )
            {
                return 0;
            }
            else if ( res == null )
            {
                return this._BasicDAL.Add(set);
            }
            else if ( res.PagePath == set.PagePath )
            {
                return res.Id;
            }
            this._BasicDAL.SetPagePath(res.Id, set.PagePath);
            return res.Id;
        }
    }
}
